#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import datetime
import json


def model_to_dict(model, fields=None):
    """
    将 Flask SQLAlchemy 的模型对象转换为字典类型
    :param: model : 模型对象
    :param: fields : 需要获取的字段列表，默认为 None，获取全部字段
    :return: 返回字典类型
    """

    if fields is None:
        # 获取所有列名
        columns = [column.name for column in model.__table__.columns]
        fields = list(columns)

    obj_dict = {}
    for field in fields:
        if field not in model.__dict__:
            continue

        value = model.__dict__[field]
        if isinstance(value, datetime.datetime):
            value = value.strftime('%Y-%m-%d %H:%M:%S')
        if isinstance(value, datetime.date):
            value = value.strftime('%Y-%m-%d')
        if isinstance(value, str):
            try:
                value = json.loads(value)
            except Exception as _:
                pass

        obj_dict[field] = value

    return obj_dict

